﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using Store.DateModel;

public partial class Pages_WebControls_AlsoPurchased : System.Web.UI.UserControl
{
    private int _ProductID;
    private int numberOfProducts = 5;
    private StoreApplicationService sas = new StoreApplicationService();

    public int ProductID
    {
        get { return _ProductID; }
        set { _ProductID = Convert.ToInt32(value); }
    }

    //------------------------------------------------------------------------------------------------------------------------------------------+
    protected void Page_PreRender(object sender, EventArgs e)
    {
        if (_ProductID > 0)
        {
            int ProductCount = 0;
            using (StoreDBEntitiesConnection db = new StoreDBEntitiesConnection())
            {
                try
                {
                    var v = db.SelectPurchasedWithProduct(_ProductID);
                    ProductCount = v.Count();
                }
                catch (Exception exp)
                {
                    throw new Exception("ERROR: Unable to Retrieve Also Purchased Items - " + exp.Message.ToString(), exp);
                }
            }

            if (ProductCount > 0)
            {
                WriteAlsoPurchased(_ProductID);
            }
            else
            {
                WritePopularItems();
            }
        }
    }

    //------------------------------------------------------------------------------------------------------------------------------------------+
    private void WriteAlsoPurchased(int currentProduct)
    {
        using (StoreDBEntitiesConnection db = new StoreDBEntitiesConnection())
        {
            try
            {
                var v = db.SelectPurchasedWithProduct(currentProduct);
                RepeaterItemsList.DataSource = v;
                RepeaterItemsList.DataBind();
            }
            catch (Exception exp)
            {
                throw new Exception("ERROR: Unable to Write Also Purchased - " + exp.Message.ToString(), exp);
            }
        }
    }

    //------------------------------------------------------------------------------------------------------------------------------------------+
    private void WritePopularItems()
    {
        try
        {
            var query = sas.GetMostPopularProducts(numberOfProducts);

            RepeaterItemsList.DataSource = query;
            RepeaterItemsList.DataBind();
        }
        catch (Exception exp)
        {
            throw new Exception("ERROR: Unable to Load Popular Items - " + exp.Message.ToString(), exp);
        }

    }
    public int NumberOfProducts
    {
        get { return numberOfProducts; }
        set { numberOfProducts = value; }
    }
}

